﻿using Qy.Core;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class DocCatService : QyRepository<DocCat>
{
    private readonly UserDeptService _userDeptService;

    public DocCatService(UserDeptService userDeptService, ApplicationContext applicationContext) : base(applicationContext)
    {
        _userDeptService = userDeptService;
    }

    /// <summary>
    /// 全部列表 缓存
    /// </summary>
    /// <returns></returns>
    public async Task<List<DocCat>> GetAllAsync()
    {
        return await GetAllListAsync("Sort asc");
    }


    /// <summary>
    /// 根据 CID 获取 一条栏目缓存数据
    /// </summary>
    /// <returns></returns>
    public async Task<DocCat> GetInfo(int cid)
    {
        List<DocCat> cates = await GetAllAsync();
        return cates.FirstOrDefault(a => a.Id == cid);
    }

    public async Task<bool> DeleteDelCache(int id)
    {
        bool resA = await Context.Queryable<DocPost>().AnyAsync(it => it.Cid == id);
        bool resB = await Context.Queryable<DocReceived>().AnyAsync(it => it.Cid == id);
        if (!resA && !resB)
            return await DeleteAndDelCacheAsync(id) > 0;
        return false;
    }

    /// <summary>
    /// 根据权限获取栏目列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<DocCat>> CateRoleListAsync(IEnumerable<int> cids, int type = 0)
    {
        List<DocCat> cates = await GetAllAsync();
        cates = cates.Where(x => x.Status == true).ToList();
        if (cids == null) return cates.Where(o => o.Type == type).ToList();
        List<DocCat> newCates = new();
        foreach (int cid in cids)
        {
            DocCat cate = new();
            if (type == 0) cate = cates.FirstOrDefault(o => o.Id == cid);
            else cate = cates.FirstOrDefault(o => o.Type == type && o.Id == cid);
            if (cate != null) newCates.Add(cate);
        }
        return newCates;
    }
    /// <summary>
    /// 树形列表
    /// </summary>
    public async Task<IEnumerable<CategoryViewModel>> GetCatTree(ILoginUserInfo userInfo)
    {
        List<DocCat> cates;
        if (userInfo.GroupId != 1)
        {
            IEnumerable<int> cateIdChannl = await GetRoleChannlAsync(userInfo.DeptId);
            cates = await CateRoleListAsync(cateIdChannl);
        }
        else cates = await GetAllAsync();
        List<CategoryViewModel> treeModels = new();
        var cateModels = cates.AsViewCategoryModels();
        CategoryExtensions.IndentedContentCates(cateModels, treeModels);
        return treeModels;
    }

    //获取当前用户部门的栏目权限信息
    public async Task<IEnumerable<int>> GetRoleChannlAsync(int deptId)
    {
        try
        {
            UserDept userDept = await _userDeptService.GetInfo(deptId);
            return JsonSerializer.Deserialize<IEnumerable<int>>(userDept.DocCatRole);
        }
        catch
        {
            return null;
        }
    }
    /// <summary>
    /// 转换带层级符号树形
    /// </summary>
    /// <param name="user"></param>
    /// <param name="role"></param>
    /// <returns></returns>
    public async Task<IEnumerable<CategoryViewModel>> GetCateListAsync(ILoginUserInfo user, int role = 0)
    {
        List<DocCat> cates;
        if (role == (int)AdminRoleEnum.Role.判断权限 && user.GroupId != 1)
        {
            IEnumerable<int> cateIdChannl = await GetRoleChannlAsync(user.DeptId);
            cates = await CateRoleListAsync(cateIdChannl);
        }
        else cates = await GetAllAsync();
        return cates.AsCateListItems();//导出带 封装数据
    }
    /// <summary>
    /// 按类型输出实体列表
    /// </summary>
    /// <param name="adminUser"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<IEnumerable<DocCat>> CategoryListAsync(ILoginUserInfo user, int type = 0)
    {
        if (user.GroupId == 1)
            return await CateRoleListAsync(null, type);
        IEnumerable<int> cateIdChannl = await GetRoleChannlAsync(user.DeptId);
        return await CateRoleListAsync(cateIdChannl, type);
    }
    /// <summary>
    /// 管理列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<ViewDocCat>> GetCategorys()
    {
        return await GetCates(0, await GetAllAsync());
    }


    /// <summary>
    /// 递归树
    /// </summary>
    /// <param name="pid">父级Id</param>
    /// <param name="cates">数据源</param>
    /// <returns></returns>
    private async Task<List<ViewDocCat>> GetCates(int pid, List<DocCat> cates = null)
    {
        var parent = cates.Where(P => P.Pid == pid);
        List<ViewDocCat> lists = new();
        foreach (var item in parent)
        {
            ViewDocCat Childer = new()
            {
                Id = item.Id,
                Title = item.Name,
                Type = item.Type,
                ObjectId1 = item.ObjectId1,
                ObjectId2 = item.ObjectId2,
                Ico = item.Ico,
                Sort = item.Sort,
                Status = item.Status,
            };
            Childer.Children = await GetSon(Childer, cates);
            if (Childer.Children != null)
            {
                Childer.HaveChild = true;
                Childer.Open = true;
            }
            lists.Add(Childer);
        }
        async Task<List<ViewDocCat>> GetSon(ViewDocCat cates, List<DocCat> sonCates = null)
        {
            if (!sonCates.Exists(x => x.Pid == cates.Id)) return null;
            else return await GetCates(cates.Id, sonCates);
        }
        return lists.OrderBy(o => o.Sort).ThenBy(o => o.Id).ToList();
    }
}
